﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using log4net;
using AutoFacUtils;
using CashFlow.Db.Entity;
using CashFlow.Db.DAL;
using CashFlow.Web.Def;
using CashFlow.Web.Areas.SystemManage.Models.Shop.Result;
using Microsoft.Ajax.Utilities;

namespace CashFlow.Web.Areas.SystemManage.Service.Implement
{
    public class ShopService : MyService<ShopInfoEntity>, IShopService
    {
        private static ILog _logger = LogManager.GetLogger(typeof(ShopService));

        private Web.Service.IUserService GetUserService() { return AutoFacHelper.Get<Web.Service.IUserService>(); }

        public IList<ShopUserInfoModel> QueryAll2()
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var ls = db.Queryable<ShopInfoEntity>()
                           .InnerJoin<UserInfoEntity>((s, u) => s.ShopManagerUserId == u.Id)
                           .OrderBy((s, u) => s.Id)
                           .Select((s, u) => new ShopUserInfoModel
                           {
                               ShopName = s.Name,
                               ShopNo = s.ShopNo,
                               ShopManagerUserId = s.ShopManagerUserId,
                               CreateTime = s.CreateTime,
                               ShopManager = u.Name
                           })
                           .ToList();
                return ls;
            }
        }

        public IList<ShopUserInfoModel> QueryByWhere(string name)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var query = db.Queryable<ShopInfoEntity>()
                           .InnerJoin<UserInfoEntity>((s, u) => s.ShopManagerUserId == u.Id);

                if (!string.IsNullOrEmpty(name))
                {
                    query = query.Where((s, u) => s.Name.Contains(name));
                }

                var ls = query.OrderBy((s, u) => s.Id)
                              .Select((s, u) => new ShopUserInfoModel
                              {
                                  ShopName = s.Name,
                                  ShopNo = s.ShopNo,
                                  ShopManagerUserId = s.ShopManagerUserId,
                                  CreateTime = s.CreateTime,
                                  ShopManager = u.Name
                              })
                             .ToList();

                return ls;
            }
        }

        public ENewShopResult NewShop(
            int shopManagerUserId
            , string shopName
            , string shopNo)
        {
            var result = ENewShopResult.Other;

            using (var db = SqlSugarHelper.GetDb())
            {
                var ls = db.Queryable<ShopInfoEntity>().ToList();
                if (ls.Where(x => x.Name == shopName).Count() > 0)
                {
                    result = ENewShopResult.ExistShopName;
                }
                else if (ls.Where(x => x.ShopNo == shopNo).Count() > 0)
                {
                    result = ENewShopResult.ExistShopNo;
                }
                else if (ls.Where(x => x.ShopManagerUserId == shopManagerUserId).Count() > 0)
                {
                    result = ENewShopResult.ExistShopManager;
                }
                else
                {
                    var service = GetUserService();
                    var userIds = service.QueryAllChildUserIdsByUserId(
                                        shopManagerUserId
                                        , null
                                  );

                    var entities = new List<ShopUserEntity>();
                    foreach (var item in userIds)
                    {
                        entities.Add(new ShopUserEntity
                        {
                            ShopManagerUserId = shopManagerUserId,
                            UserId = item
                        });
                    }

                    var shop = new ShopInfoEntity();
                    shop.ShopNo = shopNo;
                    shop.Name = shopName;
                    shop.ShopManagerUserId = shopManagerUserId;
                    shop.CreateTime = DateTime.Now;

                    try
                    {
                        db.BeginTran();
                        int delete = db.Deleteable<ShopUserEntity>()
                                       .Where(x => userIds.Contains(x.UserId))
                                       .ExecuteCommand();
                        int insert = db.Insertable(entities).ExecuteCommand();
                        int insert2 = db.Insertable(shop).ExecuteCommand();

                        db.CommitTran();

                        result = ENewShopResult.Success;
                    }
                    catch (Exception ex)
                    {
                        db.RollbackTran();
                        _logger.Error(ex);
                    }
                }
            }

            return result;
        }
    }
}